<template>
  <div class="order-page">
    <h1>我的订单</h1>
    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="order_id" label="订单号"></el-table-column>
      <el-table-column prop="total_amount" label="总金额">
        <template #default="scope">
          ¥{{ scope.row.total_amount }}
        </template>
      </el-table-column>
      <el-table-column prop="order_status" label="状态">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.order_status)">
            {{ scope.row.order_status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="下单时间"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="viewOrderDetail(scope.row.order_id)">查看详情</el-button>
          <el-button 
            v-if="scope.row.order_status === 'pending'" 
            @click="cancelOrder(scope.row.order_id)"
          >
            取消订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="detailVisible" title="订单详情">
      <div v-if="currentOrder">
        <p>订单号：{{ currentOrder.order_id }}</p>
        <p>总金额：¥{{ currentOrder.total_amount }}</p>
        <p>状态：{{ currentOrder.order_status }}</p>
        <el-table :data="orderDetails">
          <el-table-column prop="product_name" label="商品名称"></el-table-column>
          <el-table-column prop="price" label="单价"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElNotification } from 'element-plus'

const orders = ref([])
const currentOrder = ref(null)
const orderDetails = ref([])
const detailVisible = ref(false)

const fetchOrders = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:3000/orders', {
      headers: { Authorization: `Bearer ${token}` }
    })
    orders.value = response.data
  } catch (error) {
    ElNotification.error('获取订单失败')
  }
}

const statusTagType = (status) => {
  const types = {
    completed: 'success',
    cancelled: 'info',
    pending: 'warning'
  }
  return types[status.toLowerCase()] || ''
}

const viewOrderDetail = async (orderId) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`http://localhost:3000/orders/${orderId}`, {
      headers: { Authorization: `Bearer ${token}` }
    })
    currentOrder.value = response.data.order
    orderDetails.value = response.data.details
    detailVisible.value = true
  } catch (error) {
    ElNotification.error('获取订单详情失败')
  }
}

const cancelOrder = async (orderId) => {
  try {
    // 1. 发送取消请求
    const response = await axios.post(
      `http://localhost:3000/orders/cancel/${orderId}`, 
      {}, 
      {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      }
    )
    
    // 2. 检查响应状态
    if (response.status === 200) {
      // 3. 直接更新本地状态（避免重新加载整个列表）
      const index = orders.value.findIndex(order => order.order_id === orderId)
      if (index !== -1) {
        orders.value[index].order_status = 'cancelled'
      }
      
      ElNotification.success('订单已取消')
    } else {
      ElNotification.error('取消订单失败: 未知错误')
    }
  } catch (error) {
    // 4. 更精确的错误处理
    if (error.response) {
      ElNotification.error(`取消失败: ${error.response.data.error || '服务器错误'}`)
    } else {
      ElNotification.error('网络错误，请检查连接')
    }
  }
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-page {
  padding: 20px;
}
</style>